package brwarner.game
{
	import flash.display.Sprite;
	import flash.events.Event;
	/**
	 * ...
	 * @author Brook Jensen
	 */
	public class Game extends Sprite
	{
		//List of active states
		private var _states:Array;		
		
		public function Game( w:Number, h:Number ) 
		{
			//Creates a field of the correct size
			createField( w, h );
			_states = new Array();
			
			//Create the update function
			addEventListener(Event.EXIT_FRAME, update);
		}
		
		//Update function
		private function update( e:Event )
		{
			if ( activeState() != null )
			{
				activeState().update( );
			}
		}
		
		//Creates the field
		private function createField( w:Number, h:Number ):void
		{
			graphics.clear();
			graphics.beginFill( 0 );
			graphics.drawRect(0, 0, w, h );
			graphics.endFill();
		}
		
		//Gets the active state
		public function activeState( ) : GameState
		{
			//Get newest state
			if ( _states.length <= 0 ) return null;
			else return _states[_states.length - 1] as GameState;
		}
		
		//Pops a state off the stack
		public function popState( ) : GameState
		{
			//Get the old state
			var old:GameState = activeState();
			
			//Remove it as a child
			old.running = false;
			removeChild( old );
			
			//Splice the array
			_states.splice(_states.length - 1, 1);
			
			//Resume last state
			if ( _states.length > 0 )
			{
				var next:GameState = activeState();
				next.visible = true;
				next.running = true;
			}
			
			return old;
		}
		
		//Pushes a new state onto the stack
		public function pushState( g:GameState ) : GameState
		{
			//Get last state and pause it
			if ( _states.length > 0 )
			{
				var old:GameState = activeState();
				old.running = false;
				old.visible = false;
			}
			
			//Add the new state
			_states.push(g);
			
			//Start it up
			g.visible = true;
			g.running = true;
			addChild(g);
			return g;
		}
		
	}

}